package com.lhl.shiro.shiroconfig;


import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author LHL
 * @date 2018/1/8
 */

public class StatelessAuthcFilter extends AccessControlFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(StatelessAuthcFilter.class);

    private SystemCacheManager systemCacheManager;

    public StatelessAuthcFilter(SystemCacheManager systemCacheManager) {
        this.systemCacheManager = systemCacheManager;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            String ip = null;

            String token = httpServletRequest.getHeader("token");
            String userId = httpServletRequest.getHeader("userId");
            String uri = httpServletRequest.getRequestURI();

            LOGGER.info("[用户验证] userId={},token={},ip={}", userId, token, ip);
            if (userId == null || token == null || token.isEmpty()) {
                return false;
            }
            StatelessToken statelessToken = new StatelessToken(token, userId);
            try {
                getSubject(request, response).login(statelessToken);
                HttpServletResponse httpServletResponse = (HttpServletResponse) response;
                httpServletResponse.setHeader("userId", userId);
                systemCacheManager.putToken(token, userId);
                return true;
            } catch (AuthenticationException e) {
                return false;
            }
        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("resultCode", "");
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        httpServletResponse.setContentType("text/json");
        response.getWriter().write("{\"result\":\"invalid token\"}");
        return false;
    }


    //登录失败时默认返回401状态码
    private void onLoginFail(ServletResponse response) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        httpResponse.getWriter().write("login error");
    }
}
